package com.example.supermonkeysm.security.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.supermonkeysm.security.utils.TokenUtils;
import com.example.supermonkeysm.utils.Result;
import com.example.supermonkeysm.utils.Utils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import java.io.IOException;

public class LogoutSuccess implements LogoutSuccessHandler {
    private final TokenUtils tokenUtils;
    private final RedisTemplate<String, Object> redisTemplate;

    public LogoutSuccess(TokenUtils tokenUtils, RedisTemplate<String, Object> redisTemplate) {
        this.tokenUtils = tokenUtils;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String headerToken = request.getHeader("token");
        if(StringUtils.isNotBlank(headerToken)){//如果token不为空
            Claims claims = tokenUtils.analysisToken(headerToken);
            if(claims != null){
                String username = claims.getSubject();
                RedisTemplate<String,Object> redisTemplate1 = Utils.setDataBase(redisTemplate,1);
                if (Boolean.TRUE.equals(redisTemplate1.delete(username))){
                    Result.customResult(response, HttpServletResponse.SC_OK, "成功退出登录!");
                }
            }
        }
    }
}
